package com.hsnn.medstgmini.base.std.dao.impl;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.dao.impl.BaseHibernateDAO;
import com.hsnn.medstgmini.base.dict.model.DicSys;
import com.hsnn.medstgmini.base.std.dao.StdHospInfoDao;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.base.std.model.HospInfoLog;
import com.hsnn.medstgmini.base.std.model.HospLevel;
import com.hsnn.medstgmini.base.std.model.MergeStatus;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.model.Status;
import com.hsnn.medstgmini.sys.model.RegHospInfo;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.DicSysUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;

/**
 * @category 医疗机构库
 * @author CCL
 */
@Repository
public class StdHospInfoDaoImpl extends BaseHibernateDAO implements StdHospInfoDao {

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	@Autowired
	private HibernateSqlUtil dao;

	/**
	 * @category 查询医疗机构列表
	 * @param page
	 * @param hospInfo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getHospInfoPage(Pagination page, HospInfo hospInfo) {
		//获取所有医疗机构列表
		StringBuffer sql = new StringBuffer();
		String hospClassifys = page.getConditions().get("hospClassifys");
		String hospType = page.getConditions().get("hospType");
		sql.append("SELECT sh.hosp_id hospId, sh.hosp_code hospCode, sh.hosp_name hospName, sh.hosp_spel_code, sh.org_code orgCode,")
		   .append(" sh.hosp_classify hospClassify, da.ar_fullname arfullname, sh.hosp_level_id hospLevelId, sh.status status ")
		   .append(" from std_hospinfo sh JOIN dic_area da ON sh.area_id = da.area_id ")
		   .append("LEFT JOIN dic_sysdic C ON sh.hosp_classify = C.dic_code  where  C.classify_code = :classify ");
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		//使用占位符 将医疗机构等级编码113 使用classify这个占位符替代
		params.put("classify", Constants.HOSP_CAT);
		//添加查询条件
		if (null != hospInfo) {
			if (null != hospInfo.getHospCode()&& !"".equals(hospInfo.getHospCode().trim())) {
				sql.append(" and sh.hosp_code = :hospcode");
				params.put("hospcode", hospInfo.getHospCode().trim());
			}
			if(null != hospInfo.getHospName()&& !"".equals(hospInfo.getHospName().trim())){
				sql.append(" AND (sh.hosp_name LIKE :hospname OR sh.hosp_spel_code LIKE :hospname ) ");
				params.put("hospname", "%" + hospInfo.getHospName().trim() +"%");
			}
			if(hospInfo.getHospClassify()!=null&&hospInfo.getHospClassify()!=0){
				sql.append(" and sh.hosp_classify = :hospClassify ");
				params.put("hospClassify", hospInfo.getHospClassify());
			}
			if(hospClassifys != null && hospClassifys !=""){
				sql.append(" and sh.hosp_classify = :hospClassifys ");
				params.put("hospClassifys", hospClassifys);
			}
			if(hospType != null && hospType !=""){
				sql.append(" and sh.hosp_level_id = :hospType ");
				params.put("hospType", hospType);
			}
			
			//申投诉时使用，已选中的医疗机构不再添加
			if(StringUtils.isNotBlank(hospInfo.getHospId())){
				sql.append(" and sh.hosp_id not in (:hospIds) ");
				List<String> list = new ArrayList<String>();
				String[] strId = hospInfo.getHospId().split(",");
				for(int i=0;i<strId.length;i++){
					list.add(strId[i]);
				}
				params.put("hospIds", list);
			}
			if(null != hospInfo.getArea()&&!"".equals(hospInfo.getArea().getAreaid())){
				sql.append(" and sh.area_id like :areaId");
				params.put("areaId", hospInfo.getArea().getAreaid()+"%");
			}
			if(null != hospInfo.getHospClassify()&&!"".equals(hospInfo.getHospClassify())){
				sql.append(" and sh.hosp_classify=:hospClassify");
				params.put("hospClassify", hospInfo.getHospClassify());
			}
			if(null != hospInfo.getStatus()){
				sql.append(" and sh.status = :status");
				params.put("status", hospInfo.getStatus());
			}
		}
		sql.append(" order by hosp_code desc ");
		Pagination resultPage = dao.getSqlPageMapList(sql.toString(), params, page);
		//处理Map中的医疗机构等级和医疗机构
		List<Map<String, Object>> list= (List<Map<String, Object>>) resultPage.getRows();
		for(int i = 0; i < list.size(); i++){
			Map<String, Object> map = list.get(i);
			if(null != map.get("hospClassify")){
				String hospClassify = map.get("hospClassify").toString();
			    DicSys dicSys = DicSysUtil.getDicByClassCodeAndDicCode(Constants.HOSP_CAT,hospClassify);
			    if(null != dicSys){
			    	map.put("hospType", dicSys.getDicName());
			    }
			}
		    if(null != map.get("hospLevelId")){
		    	String hospLevelName = map.get("hospLevelId").toString();
			    DicSys dicSys2 = DicSysUtil.getDicByClassCodeAndDicCode(Constants.HOSP_LEVEL,hospLevelName);
			    if(null != dicSys2){
			    	map.put("hospLevelName", dicSys2.getDicName());
			    }
		    }
		}
		return resultPage;
	}

	/**
	 * @category 根据id查询医疗机构信息
	 * @param id
	 * @return
	 */
	public HospInfo getHospInfoById(String id) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospInfo.class);
		criteria.add(Restrictions.eq("hospId", id));
		return (HospInfo) criteria.uniqueResult();
	}
	
	/**
	 * @category 根据code查询医疗机构信息
	 * @param id
	 * @return
	 */
	@Override
	public HospInfo getHospInfoByCode(String code) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospInfo.class);
		criteria.add(Restrictions.eq("hospCode", code));
		return (HospInfo) criteria.uniqueResult();
	}
	
	/**
	 * @category 根据hospCode查询医疗机构信息
	 * @param hospCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<HospInfo> getHospInfoByHospCode(String hospCode,String hospId) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from std_hospInfo where hosp_code = :hospCode and hosp_id <> :hospId ");
		Query query = session.createSQLQuery(sql.toString()).addEntity(HospInfo.class);
		query.setParameter("hospCode", hospCode);
		query.setString("hospId", hospId);
		return query.list();
	}
	
	/**
	 * @category 根据hospName查询医疗机构信息
	 * @param hospName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<HospInfo> getHospInfoByHospName(String hospName,String hospId) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sql = new StringBuffer();
		sql.append("select * from std_hospInfo where hosp_name = :hospName and hosp_id <> :hospId ");
		Query query = session.createSQLQuery(sql.toString()).addEntity(HospInfo.class);
		query.setParameter("hospName", hospName);
		query.setString("hospId", hospId);
		return query.list();
	}
	
	
	/**
	 * @category 根据id查询系统字典信息
	 * @param id
	 * @return
	 */
	public DicSys getDicSysByClassifyCodeAndDicCode(String classifyCode, String dicCode) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(DicSys.class);
		criteria.add(Restrictions.eq("classifyCode", classifyCode));
		criteria.add(Restrictions.eq("sysDicId", dicCode));
		return (DicSys) criteria.uniqueResult();
	}

	/**
	 * @category 保存医疗机构信息
	 * @param hospInfo
	 */
	public void saveHospInfo(HospInfo hospInfo, int opType) {
		Session session = sessionFactory.getCurrentSession();
		if (hospInfo != null && hospInfo.getHospInfoDetail() != null) {
			hospInfo.setUpdDateTime(new Date());
			hospInfo.getHospInfoDetail().setUpdUser(hospInfo.getUpdUser());
			hospInfo.getHospInfoDetail().setUpdDateTime(new Date());
			hospInfo.getHospInfoDetail().setHospInfo(hospInfo);
			if (opType == 1 && StringUtils.isNotBlank(hospInfo.getHospId())) {
				HospInfo oldHospInfo = getHospInfoById(hospInfo.getHospId());
				hospInfo.setStatus(oldHospInfo.getStatus());
				hospInfo.setMergeState(oldHospInfo.getMergeState());
				session.evict(oldHospInfo);
				StringBuffer sql = new StringBuffer()
				.append("	update std_hospinfo a,std_hospinfo_detail b set 	")
				.append("	a.hosp_code = ?,a.hosp_name = ?,a.hosp_spel_code = ?,a.hosp_short_name = ?,a.hosp_short_spel_code = ?,	")
				.append("	a.area_id = ?,a.org_code = ?,a.hosp_classify = ?,a.hosp_type_id = ?,a.hosp_level_id = ?,a.hosp_address = ?,	")
				.append("	a.hosp_phone = ?,a.status = ?,a.upd_datetime = ?,a.upd_user = ?, a.history_code = ?,a.merge_state = ?,	")
				.append("	b.bed_num = ?,b.incom_pat_num = ?,b.staff_num = ?,b.reg_cap = ?,b.profile = ?,b.legal_rep_name = ?,	")
				.append("	b.legal_rep_idnum = ?,b.legal_rep_telephone = ?,b.legal_rep_handphone = ?,b.contact_name = ?,b.contact_idnum = ?,	")
				.append("	b.contact_pos = ?,b.contact_telephone = ?,b.contact_handphone = ?,b.contact_email = ?,b.contact_qq = ?,	")
				.append("	b.hosp_lice_no = ?,b.hosp_lice_start_date = ?,b.hosp_lice_end_date = ?,b.enter_lice_no = ?,b.enter_lice_start_date = ?,	")
				.append("	b.enter_lice_end_date = ?,b.upd_datetime = ?,b.upd_user = ?  where a.hosp_id = ? and b.hosp_id = ? ");
				Query query = session.createSQLQuery(sql.toString());
				
				query.setParameter(0, hospInfo.getHospCode());
				query.setParameter(1, hospInfo.getHospName());
				query.setParameter(2, hospInfo.getHospSpelCode());
				query.setParameter(3, hospInfo.getHospShortName());
				query.setParameter(4, hospInfo.getHospShortSpelSode());
				query.setParameter(5, hospInfo.getArea().getAreaid());
				query.setParameter(6, hospInfo.getOrgCode());
				query.setParameter(7, hospInfo.getHospClassify());
				if(hospInfo.getHosptype()==null){
					query.setParameter(8, null); 
				}else{
					query.setParameter(8, hospInfo.getHosptype().getHospTypeId());
				}
				
				query.setParameter(9, hospInfo.getHospLevelId());
				query.setParameter(10, hospInfo.getHospAddress());
				query.setParameter(11, hospInfo.getHospPhone());
				query.setParameter(12, hospInfo.getStatus());
				query.setParameter(13, hospInfo.getUpdDateTime());
				query.setParameter(14, hospInfo.getUpdUser());
				query.setParameter(15, hospInfo.getHistoryCode());
				query.setParameter(16, hospInfo.getMergeState());
				
				query.setParameter(17, hospInfo.getHospInfoDetail().getBedNum());
				query.setParameter(18, hospInfo.getHospInfoDetail().getIncomPatNum());
				query.setParameter(19, hospInfo.getHospInfoDetail().getStaffNum());
				query.setParameter(20, hospInfo.getHospInfoDetail().getRegCap());
				query.setParameter(21, hospInfo.getHospInfoDetail().getProfile());
				query.setParameter(22, hospInfo.getHospInfoDetail().getLegalRepName());
				query.setParameter(23, hospInfo.getHospInfoDetail().getLegalRepIdnum());
				query.setParameter(24, hospInfo.getHospInfoDetail().getLegalRepTelephone());
				query.setParameter(25, hospInfo.getHospInfoDetail().getLegalRepHandphone());
				query.setParameter(26, hospInfo.getHospInfoDetail().getContactName());
				query.setParameter(27, hospInfo.getHospInfoDetail().getContactIdnum());
				query.setParameter(28, hospInfo.getHospInfoDetail().getContactPos());
				query.setParameter(29, hospInfo.getHospInfoDetail().getContactTelephone());
				query.setParameter(30, hospInfo.getHospInfoDetail().getContactHandphone());
				query.setParameter(31, hospInfo.getHospInfoDetail().getContactEmail());
				query.setParameter(32, hospInfo.getHospInfoDetail().getContactQQ());
				query.setParameter(33, hospInfo.getHospInfoDetail().getHospLiceNo());
				query.setParameter(34, hospInfo.getHospInfoDetail().getHospLiceStartDate());
				query.setParameter(35, hospInfo.getHospInfoDetail().getHospLiceEndDate());
				query.setParameter(36, hospInfo.getHospInfoDetail().getEnterLiceNo());
				query.setParameter(37, hospInfo.getHospInfoDetail().getEnterLiceStartDate());
				query.setParameter(38, hospInfo.getHospInfoDetail().getEnterLiceEndDate());
				query.setParameter(39, hospInfo.getHospInfoDetail().getUpdDateTime());
				query.setParameter(40, hospInfo.getHospInfoDetail().getUpdUser());
				query.setParameter(41, hospInfo.getHospId());
				query.setParameter(42, hospInfo.getHospId());
				query.executeUpdate();
				session.flush();
				writeLog(hospInfo.getHospId());
			} else {
				if (StringUtils.isBlank(hospInfo.getHospId())) {
					hospInfo.setHospId(UUID.randomUUID().toString());
				}
				hospInfo.setStatus(Status.enabled.getKey());
				hospInfo.setMergeState(MergeStatus.unprocessed.getKey());
				StringBuffer sql1 = new StringBuffer()
				.append("insert into std_hospinfo values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
				Query query1 = session.createSQLQuery(sql1.toString());
				query1.setParameter(0, hospInfo.getHospId());
				query1.setParameter(1, hospInfo.getFatherHospCode());
				query1.setParameter(2, hospInfo.getHospCode());
				query1.setParameter(3, hospInfo.getHospName());
				query1.setParameter(4, hospInfo.getHospSpelCode());
				query1.setParameter(5, hospInfo.getHospShortName());
				query1.setParameter(6, hospInfo.getHospShortSpelSode());
				query1.setParameter(7, hospInfo.getArea().getAreaid());
				query1.setParameter(8, hospInfo.getPhiAreaId());
				query1.setParameter(9, hospInfo.getOrgCode());
				query1.setParameter(10, hospInfo.getHospClassify());
				if(hospInfo.getHosptype()== null){
					query1.setParameter(11, null);
				}else{
					query1.setParameter(11, hospInfo.getHosptype().getHospTypeId());
				}
				
				query1.setParameter(12, hospInfo.getHospLevelId());
				query1.setParameter(13, hospInfo.getHospAddress());
				query1.setParameter(14, hospInfo.getHospPhone());
				query1.setParameter(15, hospInfo.getStatus());
				query1.setParameter(16, hospInfo.getUpdDateTime());
				query1.setParameter(17, hospInfo.getUpdUser());
				query1.setParameter(18, hospInfo.getHistoryCode());
				query1.setParameter(19, hospInfo.getMergeState());
				query1.executeUpdate();
				
				StringBuffer sql2 = new StringBuffer()
				.append("insert into std_hospinfo_detail values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
				Query query2 = session.createSQLQuery(sql2.toString());
				query2.setParameter(0, hospInfo.getHospId());
				query2.setParameter(1, hospInfo.getHospInfoDetail().getBedNum());
				query2.setParameter(2, hospInfo.getHospInfoDetail().getIncomPatNum());
				query2.setParameter(3, hospInfo.getHospInfoDetail().getStaffNum());
				query2.setParameter(4, hospInfo.getHospInfoDetail().getRegCap());
				query2.setParameter(5, hospInfo.getHospInfoDetail().getProfile());
				query2.setParameter(6, hospInfo.getHospInfoDetail().getLegalRepName());
				query2.setParameter(7, hospInfo.getHospInfoDetail().getLegalRepIdnum());
				query2.setParameter(8, hospInfo.getHospInfoDetail().getLegalRepTelephone());
				query2.setParameter(9, hospInfo.getHospInfoDetail().getLegalRepHandphone());
				query2.setParameter(10, hospInfo.getHospInfoDetail().getContactName());
				query2.setParameter(11, hospInfo.getHospInfoDetail().getContactIdnum());
				query2.setParameter(12, hospInfo.getHospInfoDetail().getContactPos());
				query2.setParameter(13, hospInfo.getHospInfoDetail().getContactTelephone());
				query2.setParameter(14, hospInfo.getHospInfoDetail().getContactHandphone());
				query2.setParameter(15, hospInfo.getHospInfoDetail().getContactEmail());
				query2.setParameter(16, hospInfo.getHospInfoDetail().getContactQQ());
				query2.setParameter(17, hospInfo.getHospInfoDetail().getHospLiceNo());
				query2.setParameter(18, hospInfo.getHospInfoDetail().getHospLiceStartDate());
				query2.setParameter(19, hospInfo.getHospInfoDetail().getHospLiceEndDate());
				query2.setParameter(20, hospInfo.getHospInfoDetail().getEnterLiceNo());
				query2.setParameter(21, hospInfo.getHospInfoDetail().getEnterLiceStartDate());
				query2.setParameter(22, hospInfo.getHospInfoDetail().getEnterLiceEndDate());
				query2.setParameter(23, hospInfo.getHospInfoDetail().getUpdDateTime());
				query2.setParameter(24, hospInfo.getHospInfoDetail().getUpdUser());
				query2.executeUpdate();
				session.flush();
				writeLog(hospInfo.getHospId());
			}
			//writeLog(hospInfo.getHospId());
		}
	}

	
	
	/**
	 * @category 批量(启用|停用)
	 * @param list
	 */
	@SuppressWarnings("unchecked")
	public void batchChangeStatus(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String status = page.getConditions().get("status");
		String updUser = page.getConditions().get("updUser");
		List<String> idList = (List<String>) page.getForm();
		StringBuffer sql = new StringBuffer()
		.append("update std_hospinfo a,std_hospinfo_detail b set a.status = :status,"
				+ "a.upd_datetime = :updDatetime,"
				+ "a.upd_user = :updUser,"
				+ "b.upd_datetime = :updDatetime,"
				+ "b.upd_user = :updUser "
				+ "where a.hosp_id in (:idList) "
				+ "and "
				+ "a.hosp_id = b.hosp_id ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("status", status);
		query.setString("updDatetime", ParseDate.parseFullFormat(new Date()));
		query.setString("updUser", updUser);	
		query.setParameterList("idList", idList);
		query.executeUpdate();
		session.flush();
		/*for(int i = 0;i<idList.size();i++){
			writeLog(idList.get(i));
		}*/
	}
	/**
	 * @category 记录日志
	 * @param hospInfo
	 */
	@SuppressWarnings("unchecked")
	private void writeLog(String idList) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer detail = new StringBuffer();
		StringBuffer sql11 = new StringBuffer()
		.append(" select hosp_code,hosp_name,hosp_spel_code,hosp_short_name,hosp_short_spel_code,area_id,org_code,  ")
		.append(" hosp_classify,hosp_type_id,hosp_level_id,hosp_address,hosp_phone,  ")
		.append(" history_code,merge_state,status ")
		.append(" from std_hospinfo where hosp_id=:hospId  ")
		.append(" union all   ")
		.append(" select b.*  ") 
		.append(" from (select hosp_code,hosp_name,hosp_spel_code,hosp_short_name,hosp_short_spel_code,area_id,org_code,  ")
		.append(" hosp_classify,hosp_type_id,hosp_level_id,hosp_address,hosp_phone,  ")
		.append(" history_code,merge_state,status  ")
		.append(" from std_hospinfo_log  where hosp_id=:hospId order by upd_datetime desc limit 1)b  ");
		StringBuffer sql22 = new StringBuffer()
		.append(" select bed_num,incom_pat_num,staff_num,reg_cap,profile,legal_rep_name,legal_rep_idnum,  ")
		.append(" legal_rep_telephone,legal_rep_handphone,contact_name,contact_idnum,contact_pos,  ")
		.append(" contact_telephone,contact_handphone,contact_email,contact_qq,hosp_lice_no,hosp_lice_start_date hospLiceStartDate,  ")
		.append(" hosp_lice_end_date hospLiceEndDate,enter_lice_no,enter_lice_start_date enterLiceStartDate,enter_lice_end_date enterLiceEndDate  ")
		.append(" from std_hospinfo_detail where hosp_id=:hospId  ")
		.append(" union all   ")
		.append(" select b.*  ")
		.append(" from (select bed_num,incom_pat_num,staff_num,reg_cap,profile,legal_rep_name,legal_rep_idnum,  ")
		.append(" legal_rep_telephone,legal_rep_handphone,contact_name,contact_idnum,contact_pos,  ")
		.append(" contact_telephone,contact_handphone,contact_email,contact_qq,hosp_lice_no,hosp_lice_start_date hospLiceStartDate,  ")
		.append(" hosp_lice_end_date hospLiceEndDate,enter_lice_no,enter_lice_start_date enterLiceStartDate,enter_lice_end_date enterLiceEndDate  ")
		.append(" from std_hospinfo_detail_log  where hosp_id=:hospId order by upd_datetime desc limit 1)b  ");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("hospId", idList);
		List<?> list = dao.getSqlList(sql11.toString(), params);
		
		String[] Name = {"医疗机构编码","医疗机构名称","医疗机构名称拼音码","医疗机构简称","医疗机构简称拼音码","注册地行政区划代码","组织机构代码","医疗机构分类","医疗机构类型","医疗机构等级","机构地址","机构电话","历史医疗机构编码","合并处理状态","状态"};
		if(list.size()==1){
			Object[] obj = (Object[]) list.get(0);
			obj[14] = obj[14]==null?"":"1".equals(obj[14].toString())?"启用":"停用";
			for(int i=0;i<obj.length;i++){
				detail.append(";").append(Name[i]).append(":").append(obj[i]==null?"":obj[i].toString());
			}
			detail.delete(0, 1);
		}else{
			Object[] obj1= (Object[]) list.get(0);//修改后
			Object[] obj2= (Object[]) list.get(1);//修改前
			obj1[14] = obj1[14]==null?"":"1".equals(obj1[14].toString())?"启用":"停用";
			obj2[14] = obj2[14]==null?"":"1".equals(obj2[14].toString())?"启用":"停用";
			for(int i=0;i<obj2.length;i++){
				String a = obj1[i]==null?"":obj1[i].toString();
				String b = obj2[i]==null?"":obj2[i].toString();
				if(!(a).equals(b)){
					detail.append(";").append(Name[i]).append(":").append(obj2[i]==null?"":obj2[i].toString()).append(",").append(obj1[i]==null?"":obj1[i].toString());
				}
			}
		}
		List<Object[]> list2 = (List<Object[]>) dao.getSqlList(sql22.toString(), params);
		for(Object[] obj:list2){
			obj[17] = DateUtil.date((Timestamp)obj[17]);
			obj[18] = DateUtil.date((Timestamp)obj[18]);
			obj[20] = DateUtil.date((Timestamp)obj[20]);
			obj[21] = DateUtil.date((Timestamp)obj[21]);
		}
		String[] Name2 = {"床位数","年门诊量","员工数","注册资本","简介","法人姓名","法人身份证号","法人电话","法人手机","联系人姓名","联系人身份证号","联系人职务","联系人电话","联系人手机","联系人邮箱","联系人QQ","医疗机构执业许可证号","执业许可证号有效期始","执业许可证号有效期止","事业单位法人证书号","事业单位法人证书有效期始","事业单位法人证书有效期止"};
		if(list2.size()==1){
			Object[] obj = (Object[]) list2.get(0);
			for(int i=0;i<obj.length;i++){
				detail.append(";").append(Name2[i]).append(":").append(obj[i]==null?"":obj[i].toString());
			}
		}else{
			Object[] obj1= (Object[]) list2.get(0);
			Object[] obj2= (Object[]) list2.get(1);
			for(int i=0;i<obj2.length;i++){
				if(!(obj1[i]==null?"":obj1[i].toString()).equals(obj2[i]==null?"":obj2[i].toString())){
					detail.append(";").append(Name2[i]).append(":").append(obj2[i]==null?"":obj2[i].toString()).append(",").append(obj1[i]==null?"":obj1[i].toString());
				}
			}
			detail.delete(0, 1);
		}
		String uuid = UUID.randomUUID().toString();
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into std_hospinfo_log(log_id,hosp_id,father_hosp_code,hosp_code,hosp_name,hosp_spel_code,hosp_short_name,hosp_short_spel_code,"
				+ "  area_id,phi_area_id,org_code,hosp_classify,hosp_type_id,hosp_level_id,hosp_address,hosp_phone, status,upd_datetime,upd_user,history_code,merge_state,detail)"
				+ "  select :uuid,a.*,:detail from std_hospinfo a where a.hosp_id = :hospId ");
		StringBuffer sql2 = new StringBuffer()
		.append("   insert into std_hospinfo_detail_log(log_id,hosp_id,bed_num,incom_pat_num,staff_num,reg_cap,profile,"
				+ " legal_rep_name,legal_rep_idnum,legal_rep_telephone,legal_rep_handphone,contact_name,contact_idnum,contact_pos, contact_telephone,contact_handphone,contact_email,contact_qq,"
				+ " hosp_lice_no,hosp_lice_start_date,hosp_lice_end_date,enter_lice_no,enter_lice_start_date,enter_lice_end_date,upd_datetime,upd_user,detail)"
				+ " select :uuid,b.*,:detail from std_hospinfo_detail b where b.hosp_id = :hospId ");
		Query query=session.createSQLQuery(sql.toString());
		query.setString("uuid", uuid);
		query.setString("hospId", idList);
		query.setString("detail", detail.toString());
		query.executeUpdate();
		session.flush();
		Query query2=session.createSQLQuery(sql2.toString());
		query2.setString("uuid", uuid);
		query2.setString("hospId", idList);
		query2.setString("detail", detail.toString());
		query2.executeUpdate();
		session.flush();
	}

	/**
	 * @category 查询医疗机构维护记录列表
	 * @param page
	 * @param hospInfoLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getHospInfoLogPage(Pagination page,HospInfoLog hospInfoLog) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT A.log_id logId, A.hosp_id hospId, A.hosp_code hospCode, A.hosp_name hospName,A.hosp_level_id hospLevelName, ")
		   .append("A.hosp_spel_code hospSpelCode, A.hosp_short_name hospShortName, A.hosp_short_spel_code hospShortSpelCode, ")
		   .append("A.org_code orgCode, A.status statusName, date_format(A.upd_datetime,'%Y-%m-%d %T') updDateTimeStr, p.name updUser, B.ar_fullname hospAddress, C.dic_name hospType,A.detail detail ")
		   .append("FROM std_hospinfo_log A JOIN dic_area B on A.area_id = B.area_id left join sys_user p on p.id = A.upd_user ")
		   .append("JOIN dic_sysdic C ON A.hosp_classify = C.dic_code and C.classify_code = 113 where hosp_id = :hospId ");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hospId", hospInfoLog.getHospId());
		if(null != hospInfoLog){
			if(null != hospInfoLog.getStartTime() && !"".equals(hospInfoLog.getStartTime())){
				sql.append("and A.upd_datetime > :startTime ");
				params.put("startTime", hospInfoLog.getStartTime());
			}
			if(null != hospInfoLog.getEndTime()&& !"".equals(hospInfoLog.getEndTime())){
				sql.append("and A.upd_datetime < :endTime ");
				params.put("endTime", hospInfoLog.getEndTime());
			}
		}
		sql.append("order by A.upd_datetime DESC ");
		Pagination resultPage =  dao.getSqlPageMapList(sql.toString(), params, page);
		//转换日期
		List<Map<String, String>>  list = (List<Map<String, String>>) resultPage.getRows();
		for(int i = 0; i < list.size(); i++){
			Map<String, String> map = list.get(i);
			map.put("hospLevelName", HospLevel.getName(list.get(i).get("hospLevelName")));
		}
		return resultPage;
	}


	

	/**
	 * @category 查询维护记录修改前修改后记录
	 * @param hospInfoLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String,Object>> getHospCompareList(HospInfoLog hospInfoLog) {
		StringBuffer sql = new StringBuffer()
		.append("	select h.hosp_code hospCode,h.hosp_name hospName,h.hosp_short_name hospShortName,h.org_code orgCode,   ")
		.append("	c.dic_name hospClassifyName,d.hosp_type hospType,h.hosp_level_id hospLevelName,h.hosp_address hospAddress,h.hosp_phone hospPhone, ")
		.append("	hd.bed_num bedNum,hd.incom_pat_num incomPatNum,hd.staff_num staffNum,hd.reg_cap regCap,hd.legal_rep_name legalRepName,")
		.append("	hd.legal_rep_idnum legalRepIdnum,hd.legal_rep_telephone legalRepTelephone,hd.legal_rep_handphone legalRepHandphone,")
		.append("	hd.contact_name contactName,hd.legal_rep_idnum contactIdnum,hd.contact_pos contactPos,hd.contact_telephone contactTelephone,")
		.append("	hd.contact_handphone contactHandphone,hd.contact_email contactEmail,hd.contact_qq contactQQ,hd.hosp_lice_no hospLiceNo,")
		.append("	DATE_FORMAT(hd.hosp_lice_start_date,'%Y-%m-%d') hospLiceStartDate,DATE_FORMAT(hd.hosp_lice_end_date,'%Y-%m-%d') hospLiceEndDate,e.ar_fullname arfullname,hd.enter_lice_no enterLiceNo,")
		.append("	DATE_FORMAT(hd.hosp_lice_start_date,'%Y-%m-%d') enterLiceStartDate,DATE_FORMAT(hd.hosp_lice_end_date,'%Y-%m-%d') enterLiceEndDate,h.status status,hd.profile profile")
		.append("   ,DATE_FORMAT(hd.upd_datetime,'%Y-%m-%d %T')  updDatetime, s.name updUser ")
		.append("	from  std_hospinfo_detail_log hd,std_hospinfo_log h left join dic_sysdic c on c.dic_code = h.hosp_classify left join dic_hosptype d on d.hosp_type_id = h.hosp_type_id   ")
		.append("   left join sys_user s on s.id=h.upd_user ")
		.append("   left join dic_area e on e.area_id = h.area_id ")
		.append("	where c.classify_code = :classify and h.log_id = hd.log_id and h.hosp_id = :hospId ")
		.append("	and h.upd_datetime <= (select upd_datetime from std_hospinfo_log where log_id = :logId) order by h.upd_datetime desc limit 2");
		Map<String,String> params = new HashMap<String,String>();
		params.put("classify", Constants.HOSP_CAT);
		params.put("hospId", hospInfoLog.getHospId());
		params.put("logId", hospInfoLog.getLogId());
		List<Map<String,Object>> list = (List<Map<String,Object>>) dao.getSqlMapList(sql.toString(), params);
		if(list!=null&&list.size()>0){
			for(int i = 0;i<list.size();i++){
				list.get(i).put("hospLevelName", HospLevel.getName(list.get(i).get("hospLevelName")==null?"":list.get(i).get("hospLevelName").toString()));
			}
		}
		
		return list;
	}

	/**
	 * @category 校验注册的医疗机构在医疗机构库中是否存在
	 * @date 2015年6月24日
	 * @param hospInfo
	 * @return
	 */
	public boolean checkHospExist(RegHospInfo hospInfo) {
		Session session = sessionFactory.getCurrentSession();
		if (hospInfo != null) {
			StringBuffer sql = new StringBuffer()
			.append("select count(*) from std_hospinfo where hosp_name = :hospName ");
			Query query = session.createSQLQuery(sql.toString());
			query.setString("hospName", hospInfo.getHospName());
			Long records = Long.parseLong(query.uniqueResult().toString());
			if (records != null && records > 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @category 获取存在的医疗机构
	 * @date 2015年6月24日
	 * @param hospInfo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public HospInfo getExistHosp(RegHospInfo hospInfo) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospInfo.class);
		if (hospInfo != null) {
			criteria.add(Restrictions.eq("hospName", hospInfo.getHospName()));
			List<HospInfo> list = criteria.list();
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		}
		return null;
	}
	
	/**
	 * 根据条件获取不分页数据
	 * @param page
	 * @return page
	 */
	@Override
	public Pagination getStdHospinfoNoPage(Pagination page){
		Map<String,String> params = new HashMap<String, String>();
		String hospCode = page.getConditions().get("hospCode");
		String hospName = page.getConditions().get("hospName");
		String hospClassify = page.getConditions().get("hospClassify");
		String areaId = page.getConditions().get("areaId");
		String status = page.getConditions().get("status");
		StringBuffer sql = new StringBuffer()
		.append("	SELECT a.hosp_code hospCode,a.hosp_name hospName,a.hosp_spel_code hospSpelCode,")
		.append("	a.hosp_short_name hospShortName,a.hosp_short_spel_code hospShortSpelCode,")
		.append("	c.ar_fullname areaId,a.org_code orgCode,d.dic_name hospClassify,e.hosp_type  hospTypeId,")
		.append("	f.dic_name hospLevelId,a.hosp_address hospAddress,a.hosp_phone hospPhone,a.history_code historyCode,")
		.append("	CASE a.merge_state WHEN '1' THEN '已处理' ELSE '未处理' END mergeState,")
		.append("	CASE a.status WHEN '0' THEN '停用' ELSE '启用' END status,")
		.append("	b.bed_num bedNum,b.incom_pat_num incomPatNum,b.staff_num staffNum,b.reg_cap regCap,b.profile profile,")
		.append("	b.legal_rep_name legalRepName,b.legal_rep_idnum legalRepIdnum,b.legal_rep_telephone legalRepTelephone,")
		.append("	b.legal_rep_handphone legalRepHandphone,b.contact_name contactName,b.contact_idnum contactIdnum,")
		.append("	b.contact_pos contactPos,b.contact_telephone contactTelephone,b.contact_handphone contactHandphone,")
		.append("	b.contact_email contactEmail,b.contact_qq contactQq,b.hosp_lice_no hospLiceNo,")
		.append("	DATE_FORMAT(b.hosp_lice_start_date,'%Y-%m-%d') hospLiceStartDate,")
		.append("	DATE_FORMAT(b.hosp_lice_end_date,'%Y-%m-%d') hospLiceEndDate,b.enter_lice_no enterLiceNo,")
		.append("	DATE_FORMAT(b.enter_lice_start_date,'%Y-%m-%d') enterLiceStartDate,")
		.append("	DATE_FORMAT(b.enter_lice_end_date,'%Y-%m-%d') enterLiceEndDate")
		.append("	FROM std_hospinfo a JOIN std_hospinfo_detail b ON b.hosp_id = a.hosp_id")
		.append("	JOIN dic_area c ON c.area_id = a.area_id ")
		.append("	LEFT JOIN dic_sysdic d ON d.dic_code = a.hosp_classify AND d.classify_code = :classify")
		.append("	LEFT JOIN dic_hosptype e ON e.hosp_type_id = a.hosp_type_id ")
		.append("	LEFT JOIN dic_sysdic f ON f.dic_code = a.hosp_classify AND f.classify_code = :classifySon")
		.append("	WHERE 1 = 1");
		params.put("classify", Constants.HOSP_CAT);
		params.put("classifySon", Constants.HOSP_LEVEL);
		if(StringUtils.isNotBlank(hospCode)){
			sql.append(" and a.hosp_code = :hospCode ");
			params.put("hospCode", hospCode);
		}
		if(StringUtils.isNotBlank(hospName)){
			sql.append(" and a.hosp_name like :hospName ");
			params.put("hospName", "%"+hospName+"%");
		}
		if(StringUtils.isNotBlank(hospClassify)){
			sql.append(" and a.hosp_classify = :hospClassify ");
			params.put("hospClassify", hospClassify);
		}
		if(StringUtils.isNotBlank(areaId)){
			sql.append(" and a.area_id like :areaId ");
			params.put("areaId", areaId+"%");
		}
		if(StringUtils.isNotBlank(status)){
			sql.append(" and a.status = :status ");
			params.put("status", status);
		}
		sql.append("	ORDER BY a.hosp_code ");
		page.setRows(dao.getSqlMapList(sql.toString(), params));
		return page;
	}

	@Override
	public Pagination getHospCount(Pagination page) {
		Map<String,String> params = new HashMap<String, String>();
		String areaId = page.getConditions().get("areaId");
		String projRange = page.getConditions().get("projRange");
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT  count(*) from std_hospinfo sh JOIN dic_area da ON sh.area_id = da.area_id ")
		   .append("LEFT JOIN dic_sysdic C ON sh.hosp_classify = C.dic_code  where  C.classify_code = :classify and sh.status = 1 ");
		params.put("classify", Constants.HOSP_CAT);
		if(StringUtils.isNotBlank(areaId)){
			sql.append(" and da.area_id like :areaId");
		}
		if(StringUtils.isNotBlank(projRange)){
			if(!("0".equals(projRange))){
				sql.append(" and sh.hosp_classify=:hospClassify");
			}
		}
		Query countQuery = getSession().createSQLQuery(sql.toString());
		if(StringUtils.isNotBlank(areaId)){
			countQuery.setParameter("areaId", areaId+"%");
		}
		if(StringUtils.isNotBlank(projRange)){
			if(!("0".equals(projRange))){
				countQuery.setParameter("hospClassify", projRange);	
			}
		}
		BigInteger records = (BigInteger) countQuery.uniqueResult();
		page.setRows((records.longValue()));
		return page;
	
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> getStdHospInfoByCode(String code){
		String sql = "select * from std_hospinfo t where t.hosp_code = :hospCode";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hospCode", code);
		List<Map<String, Object>> list = (List<Map<String, Object>>) dao.getSqlMapList(sql, params);
		if (null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public Map<String, Object> getStdHospInfoDetailById(String id){
		String sql = "select * from std_hospinfo_detail t where t.hosp_id= :hospId";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("hospId", id);
		List<Map<String, Object>> list = (List<Map<String, Object>>) dao.getSqlMapList(sql, params);
		if (null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
}
